/*
 * @Author: xishanxu
 * @LastEditors  : xisuanxu
 * @LastEditTime : 2019-12-22 11:43:32
 */
/* eslint-disable no-undef */
import { reloadAuthorized } from './Authorized';

const TokenKey: string = 'authority';

/**
 * @name: getAuthority
 * @Date: 2019-12-21 20:15:12
 * @LastEditors: xishanxu
 * @param {string} [str]
 * @param {string} [changeToken] 是否获取某一特定的token，如果不是默认存入authority
 * @return: string | string[]
 */
function getAuthority(str?: string): string | string[] {
  const authorityString =
    typeof str === 'undefined' && localStorage ? localStorage.getItem(TokenKey) : str;
  let authority;
  try {
    if (authorityString) {
      authority = JSON.parse(authorityString);
    }
  } catch (e) {
    authority = authorityString;
  }
  if (typeof authority === 'string') {
    return [authority];
  }
  if (!authority && ANT_DESIGN_PRO_ONLY_DO_NOT_USE_IN_YOUR_PRODUCTION === 'site') {
    return ['admin'];
  }
  return authority;
}

/**
 * @name: setAuthority
 * @Date: 2019-12-21 20:19:09
 * @LastEditors: xishanxu
 * @param {string} [authority] 存入的token值， 权限的话存admin、user这些
 * @param {string} [changeToken] 是否存入指定的token
 * @returns {undefined}
 */
function setAuthority(authority: string | string[], changeToken: string | void): void {
  if (changeToken) {
    localStorage.setItem(changeToken, JSON.stringify(authority));
  } else {
    const proAuthority = typeof authority === 'string' ? [authority] : authority;
    localStorage.setItem(TokenKey, JSON.stringify(proAuthority));
  }
  reloadAuthorized();
}

/**
 * @name: removeAuthority
 * @Date: 2019-12-21 20:19:47
 * @LastEditors: xishanxu
 * @param {type} [changeToken]
 * @returns: undefined
 */
function removeAuthority(changeToken?: string | void): void {
  if (changeToken) {
    localStorage.removeItem(changeToken);
  } else {
    localStorage.removeItem(TokenKey);
  }
}

function getToken(key: string): any {
  return localStorage.getItem(key);
}

export { getAuthority, setAuthority, removeAuthority, getToken };
